// 登录页

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:icons_plus/icons_plus.dart';

import '../tools/tools_common.dart';
import './page_album_list.dart';
import './page_register.dart';
import '../widget/widget_login_button.dart';
import '../widget/widget_login_square_tile.dart';
import '../widget/widget_login_textfield.dart';
import '../tools/tools_net.dart';

class PageLogin extends StatefulWidget {
  const PageLogin({super.key});

  @override
  State<PageLogin> createState() => _PageLoginState();
}

class _PageLoginState extends State<PageLogin> {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _codeController = TextEditingController();

  String _base64Str = "";
  String _uuid = "";

  @override
  void initState() {
    super.initState();

    op_refreshCode();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[300],
      body: SafeArea(
          child: Center(
        child: Column(
          children: [
            SizedBox(
              height: 30,
            ),
            Icon(
              ZondIcons.coffee,
              size: 80,
            ),
            SizedBox(
              height: 30,
            ),
            Text("欢迎光临,请登录您的账号!"),
            SizedBox(
              height: 25,
            ),
            WidgetLoginTextfield(
              hintText: "请输入用户名",
              obscureText: false,
              controller: _usernameController,
            ),
            SizedBox(
              height: 10,
            ),
            WidgetLoginTextfield(
              hintText: "请输入密码",
              obscureText: false,
              controller: _passwordController,
            ),
            SizedBox(
              height: 10,
            ),
            Row(
              children: [
                Expanded(
                  child: WidgetLoginTextfield(
                    hintText: "请输入验证码",
                    obscureText: false,
                    controller: _codeController,
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 25),
                  child: GestureDetector(
                    onTap: op_refreshCode,
                    child: SizedBox(
                      width: 100,
                      height: 60,
                      child: _base64Str.length > 0 ? Image.memory(base64Decode(_base64Str)) : null,
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 10,
            ),
            WidgetLoginButton(
                text: "登录",
                onTap: () {
                  op_login(context);
                }),
            SizedBox(
              height: 30,
            ),
            Row(
              children: [
                Expanded(
                    child: Divider(
                  thickness: 0.5,
                  color: Colors.grey[400],
                )),
                Text("使用短信验证码或社交账号登录"),
                Expanded(
                    child: Divider(
                  thickness: 0.5,
                  color: Colors.grey[400],
                ))
              ],
            ),
            SizedBox(
              height: 20,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Wrap(
                direction: Axis.horizontal,
                alignment: WrapAlignment.center,
                spacing: 5,
                runSpacing: 20,
                // mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  WidgetLoginSquareTile(icon: Icon(Bootstrap.telephone)),
                  SizedBox(
                    width: 10,
                  ),
                  WidgetLoginSquareTile(icon: Icon(Bootstrap.wechat)),
                  SizedBox(
                    width: 10,
                  ),
                  WidgetLoginSquareTile(icon: Icon(FontAwesome.qq_brand)),
                  SizedBox(
                    width: 10,
                  ),
                  WidgetLoginSquareTile(icon: Icon(Bootstrap.google)),
                  SizedBox(
                    width: 10,
                  ),
                  WidgetLoginSquareTile(icon: Icon(Bootstrap.facebook)),
                  SizedBox(
                    width: 10,
                  ),
                  WidgetLoginSquareTile(icon: Icon(Bootstrap.apple)),
                  SizedBox(
                    width: 10,
                  ),
                  WidgetLoginSquareTile(icon: Icon(Bootstrap.twitter_x)),
                ],
              ),
            ),
            Expanded(child: Container()),
            GestureDetector(
              onTap: () {
                op_register(context);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text("还没注册?"),
                  SizedBox(
                    width: 8,
                  ),
                  Text(
                    "立即注册",
                    style: TextStyle(color: Colors.lightBlue),
                  ),
                ],
              ),
            ),
            GestureDetector(
              onTap: () {
                op_single(context);
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Text(
                    "单机使用",
                    style: TextStyle(color: Colors.lightBlue),
                  ),
                ],
              ),
            )
          ],
        ),
      )),
    );
  }

  // 1. 刷新验证码
  op_refreshCode() {
    print("刷新验证码");
    // 请求验证码图片
    ToolsNet.requestCode().then((String value) {
      var obj = ToolsNet.parseJSON(value);
      _base64Str = obj["img"];
      _uuid = obj["uuid"];
      setState(() {});
    }).onError((e, s) {
      print(e);
      print(s);

      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("出错了"),
              content: Text("1. 请检查网络 2.联系管理员 3. 选择单机使用"),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Text("确定")),
              ],
            );
          });
    });
  }

  // 2. 登录处理
  op_login(context) {
    print("立即登录");
    String username = _usernameController.text;
    String password = _passwordController.text;
    String code = _codeController.text;

    if (username.length < 1 || password.length < 1 || code.length < 1) {
      _codeController.clear();
      op_refreshCode();
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("提示"),
              content: Text("请输入用户名密码及验证码"),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Text("确定")),
              ],
            );
          });
      return;
    }

    Map<String, dynamic> m = new Map();
    m["username"] = username;
    m["password"] = password;
    m["code"] = code;
    m["uuid"] = _uuid;

    ToolsNet.requestLogin(m).then((value) {
      var obj = ToolsNet.parseJSON(value);
      if (obj["msg"] == "操作成功") {
        ToolsNet.setToken(obj["token"]);

        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("登录成功"),
                content: Text("登录成功"),
                actions: [
                  TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) {
                          return PageAlbumList();
                        }));
                      },
                      child: Text("确定")),
                ],
              );
            });
      } else {
        print("登录失败");

        showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("登录失败"),
                content: Text('错误信息${obj["msg"]}'),
                actions: [
                  TextButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      child: Text("确定")),
                ],
              );
            });
      }
    });
    //
  }

  // 3. 注册处理
  op_register(context) {
    print("注册");
    Navigator.push(context, MaterialPageRoute(builder: (context) => PageRegister()));
  }

  // 4. 单机运行
  op_single(context) {
    ToolsCommon.applcation_model = 2;
    Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) {
      return PageAlbumList();
    }));
  }
}
